import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../data/models/upload/upload_task.dart';
import '../services/upload_service.dart';
import '../services/upload_task_factory.dart';
import '../../core/di/service_locator.dart';

/// 上传队列状态管理
class UploadQueueProvider with ChangeNotifier {
  final List<UploadTask> _tasks = [];
  final UploadService _uploadService;
  final UploadTaskFactory _uploadTaskFactory;
  bool _isProcessing = false;
  int _concurrentUploads = 3; // 并发上传数量

  UploadQueueProvider(this._uploadService)
    : _uploadTaskFactory = serviceLocator<UploadTaskFactory>();

  /// 获取所有任务
  List<UploadTask> get tasks => List.unmodifiable(_tasks);

  /// 获取正在处理的任务
  List<UploadTask> get processingTasks =>
      _tasks
          .where((task) => task.status == UploadTaskStatus.uploading)
          .toList();

  /// 获取等待中的任务
  List<UploadTask> get pendingTasks =>
      _tasks.where((task) => task.status == UploadTaskStatus.pending).toList();

  /// 获取已完成的任务
  List<UploadTask> get completedTasks =>
      _tasks
          .where((task) => task.status == UploadTaskStatus.completed)
          .toList();

  /// 获取失败的任务
  List<UploadTask> get failedTasks =>
      _tasks.where((task) => task.status == UploadTaskStatus.failed).toList();

  /// 是否正在处理任务
  bool get isProcessing => _isProcessing;

  /// 上传任务工厂
  UploadTaskFactory get uploadTaskFactory => _uploadTaskFactory;

  /// 添加任务到队列
  Future<void> addTask(UploadTask task) async {
    _tasks.add(task);
    notifyListeners();
    await _processQueue();
  }

  /// 批量添加任务
  Future<void> addTasks(List<UploadTask> tasks) async {
    _tasks.addAll(tasks);
    notifyListeners();
    await _processQueue();
  }

  /// 暂停任务
  Future<void> pauseTask(String taskId) async {
    final task = _tasks.firstWhere((t) => t.id == taskId);
    if (task.status == UploadTaskStatus.uploading) {
      task.updateStatus(UploadTaskStatus.paused);
      await _uploadService.pauseUpload(taskId);
      notifyListeners();
    }
  }

  /// 恢复任务
  Future<void> resumeTask(String taskId) async {
    final task = _tasks.firstWhere((t) => t.id == taskId);
    if (task.status == UploadTaskStatus.paused) {
      task.updateStatus(UploadTaskStatus.pending);
      notifyListeners();
      await _processQueue();
    }
  }

  /// 取消任务
  Future<void> cancelTask(String taskId) async {
    final task = _tasks.firstWhere((t) => t.id == taskId);
    if (task.status == UploadTaskStatus.uploading ||
        task.status == UploadTaskStatus.pending) {
      task.updateStatus(UploadTaskStatus.cancelled);
      await _uploadService.cancelUpload(taskId);
      notifyListeners();
    }
  }

  /// 重试失败的任务
  Future<void> retryTask(String taskId) async {
    final task = _tasks.firstWhere((t) => t.id == taskId);
    if (task.status == UploadTaskStatus.failed) {
      task.updateStatus(UploadTaskStatus.pending);
      task.errorMessage = null;
      notifyListeners();
      await _processQueue();
    }
  }

  /// 处理队列
  Future<void> _processQueue() async {
    if (_isProcessing) return;

    _isProcessing = true;
    try {
      while (_tasks.any((task) => task.status == UploadTaskStatus.pending)) {
        final pendingTasks =
            _tasks
                .where((task) => task.status == UploadTaskStatus.pending)
                .take(_concurrentUploads - processingTasks.length)
                .toList();

        if (pendingTasks.isEmpty) break;

        await Future.wait(pendingTasks.map((task) => _processTask(task)));
      }
    } finally {
      _isProcessing = false;
    }
  }

  /// 处理单个任务
  Future<void> _processTask(UploadTask task) async {
    try {
      task.updateStatus(UploadTaskStatus.uploading);
      notifyListeners();

      await _uploadService.uploadFile(
        task,
        onProgress: (progress) {
          task.updateProgress(progress);
          notifyListeners();
        },
      );

      task.updateStatus(UploadTaskStatus.completed);
    } catch (e) {
      task.updateStatus(UploadTaskStatus.failed, error: e.toString());
    } finally {
      notifyListeners();
    }
  }

  /// 清空已完成的任务
  void clearCompletedTasks() {
    _tasks.removeWhere((task) => task.status == UploadTaskStatus.completed);
    notifyListeners();
  }

  /// 清空所有任务
  void clearAllTasks() {
    _tasks.clear();
    notifyListeners();
  }
}
